<template>
  <div class="merchant-detail">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>商户详情</span>
          <div class="header-operations">
            <el-button @click="goBack">返回</el-button>
            <el-button type="primary" @click="handleEdit" v-if="merchantInfo.status !== 2">编辑</el-button>
          </div>
        </div>
      </template>

      <!-- 基本信息 -->
      <el-descriptions title="基本信息" :column="3" border>
        <el-descriptions-item label="商户名称">{{ merchantInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="商户类型">{{ getTypeLabel(merchantInfo.type) }}</el-descriptions-item>
        <el-descriptions-item label="商户状态">
          <el-tag :type="getStatusTag(merchantInfo.status)">
            {{ getStatusLabel(merchantInfo.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系人">{{ merchantInfo.contactName }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ merchantInfo.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="商户地址">{{ merchantInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="营业执照">
          <el-image 
            v-if="merchantInfo.license"
            :src="merchantInfo.license"
            :preview-src-list="[merchantInfo.license]"
            fit="cover"
            class="license-image"
          />
        </el-descriptions-item>
        <el-descriptions-item label="商户简介" :span="2">{{ merchantInfo.description }}</el-descriptions-item>
      </el-descriptions>

      <!-- 结算信息 -->
      <el-descriptions title="结算信息" :column="3" border class="mt-20">
        <el-descriptions-item label="结算账户">{{ merchantInfo.settlementAccount }}</el-descriptions-item>
        <el-descriptions-item label="开户银行">{{ merchantInfo.bankName }}</el-descriptions-item>
        <el-descriptions-item label="银行账号">{{ merchantInfo.bankAccount }}</el-descriptions-item>
        <el-descriptions-item label="待结算金额">
          <span class="amount">¥{{ merchantInfo.settlementAmount?.toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="已结算金额">
          <span class="amount">¥{{ merchantInfo.settledAmount?.toFixed(2) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="结算周期">{{ merchantInfo.settlementCycle }}</el-descriptions-item>
      </el-descriptions>

      <!-- 统计信息 -->
      <div class="statistics-cards mt-20">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>总订单数</span>
                </div>
              </template>
              <div class="card-value">{{ statistics.totalOrders }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>总销售额</span>
                </div>
              </template>
              <div class="card-value">¥{{ statistics.totalSales?.toFixed(2) }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>商品数量</span>
                </div>
              </template>
              <div class="card-value">{{ statistics.totalProducts }}</div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="statistics-card">
              <template #header>
                <div class="card-header">
                  <span>平均评分</span>
                </div>
              </template>
              <div class="card-value">{{ statistics.averageRating?.toFixed(1) }}</div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" class="mt-20">
        <!-- 订单列表 -->
        <el-tab-pane label="订单列表" name="orders">
          <el-table
            v-loading="orderLoading"
            :data="orderList"
            style="width: 100%"
            border
          >
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column prop="orderNo" label="订单编号" min-width="180" />
            <el-table-column prop="amount" label="订单金额" width="120">
              <template #default="{ row }">
                ¥{{ row.amount?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="订单状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getOrderStatusTag(row.status)">
                  {{ getOrderStatusLabel(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="下单时间" width="180" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="handleViewOrder(row)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="orderQuery.pageNum"
              v-model:page-size="orderQuery.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="orderTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleOrderSizeChange"
              @current-change="handleOrderCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 商品列表 -->
        <el-tab-pane label="商品列表" name="products">
          <el-table
            v-loading="productLoading"
            :data="productList"
            style="width: 100%"
            border
          >
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column prop="name" label="商品名称" min-width="180" />
            <el-table-column prop="price" label="价格" width="120">
              <template #default="{ row }">
                ¥{{ row.price?.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100" />
            <el-table-column prop="sales" label="销量" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'info'">
                  {{ row.status === 1 ? '上架' : '下架' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="handleViewProduct(row)"
                >
                  查看
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="productQuery.pageNum"
              v-model:page-size="productQuery.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="productTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleProductSizeChange"
              @current-change="handleProductCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 评价列表 -->
        <el-tab-pane label="评价列表" name="reviews">
          <el-table
            v-loading="reviewLoading"
            :data="reviewList"
            style="width: 100%"
            border
          >
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column prop="memberName" label="会员名称" width="120" />
            <el-table-column prop="rating" label="评分" width="100">
              <template #default="{ row }">
                <el-rate
                  v-model="row.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                />
              </template>
            </el-table-column>
            <el-table-column prop="content" label="评价内容" min-width="300" show-overflow-tooltip />
            <el-table-column prop="images" label="评价图片" width="120">
              <template #default="{ row }">
                <el-image
                  v-if="row.images && row.images.length > 0"
                  :src="row.images[0]"
                  :preview-src-list="row.images"
                  fit="cover"
                  class="review-image"
                />
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="评价时间" width="180" />
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button
                  link
                  type="primary"
                  @click="handleReplyReview(row)"
                >
                  回复
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="reviewQuery.pageNum"
              v-model:page-size="reviewQuery.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="reviewTotal"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleReviewSizeChange"
              @current-change="handleReviewCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 评价回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复评价"
      width="500px"
    >
      <el-form
        ref="replyFormRef"
        :model="replyForm"
        :rules="replyRules"
        label-width="80px"
      >
        <el-form-item label="回复内容" prop="replyContent">
          <el-input
            v-model="replyForm.replyContent"
            type="textarea"
            :rows="3"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  getMerchantDetail,
  getMerchantStatistics,
  getMerchantOrders,
  getMerchantProducts,
  getMerchantReviews,
  replyMerchantReview
} from '@/api/merchant'

const route = useRoute()
const router = useRouter()
const merchantId = route.params.id

// 商户信息
const merchantInfo = ref({})
const statistics = ref({
  totalOrders: 0,
  totalSales: 0,
  totalProducts: 0,
  averageRating: 0
})

// 状态选项
const statusOptions = [
  { label: '待审核', value: 0 },
  { label: '正常营业', value: 1 },
  { label: '已拒绝', value: 2 },
  { label: '已关闭', value: 3 }
]

// 商户类型选项
const typeOptions = [
  { label: '个人商户', value: 1 },
  { label: '企业商户', value: 2 },
  { label: '连锁商户', value: 3 }
]

// 订单状态选项
const orderStatusOptions = [
  { label: '待付款', value: 0 },
  { label: '待发货', value: 1 },
  { label: '待收货', value: 2 },
  { label: '已完成', value: 3 },
  { label: '已取消', value: 4 }
]

// 标签页
const activeTab = ref('orders')

// 订单列表
const orderLoading = ref(false)
const orderList = ref([])
const orderTotal = ref(0)
const orderQuery = ref({
  pageNum: 1,
  pageSize: 10
})

// 商品列表
const productLoading = ref(false)
const productList = ref([])
const productTotal = ref(0)
const productQuery = ref({
  pageNum: 1,
  pageSize: 10
})

// 评价列表
const reviewLoading = ref(false)
const reviewList = ref([])
const reviewTotal = ref(0)
const reviewQuery = ref({
  pageNum: 1,
  pageSize: 10
})

// 评价回复
const replyDialogVisible = ref(false)
const replyFormRef = ref(null)
const replyForm = ref({
  reviewId: undefined,
  replyContent: ''
})

// 回复表单验证规则
const replyRules = {
  replyContent: [
    { required: true, message: '请输入回复内容', trigger: 'blur' }
  ]
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    3: 'info'
  }
  return map[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const item = statusOptions.find(item => item.value === status)
  return item ? item.label : status
}

// 获取商户类型标签文本
const getTypeLabel = (type) => {
  const item = typeOptions.find(item => item.value === type)
  return item ? item.label : type
}

// 获取订单状态标签
const getOrderStatusTag = (status) => {
  const map = {
    0: 'warning',
    1: 'primary',
    2: 'success',
    3: 'info',
    4: 'danger'
  }
  return map[status] || 'info'
}

// 获取订单状态标签文本
const getOrderStatusLabel = (status) => {
  const item = orderStatusOptions.find(item => item.value === status)
  return item ? item.label : status
}

// 获取商户详情
const getMerchantInfo = async () => {
  try {
    const res = await getMerchantDetail(merchantId)
    merchantInfo.value = res.data
  } catch (error) {
    console.error('获取商户详情失败:', error)
    ElMessage.error('获取商户详情失败')
  }
}

// 获取统计数据
const getStatisticsData = async () => {
  try {
    const res = await getMerchantStatistics(merchantId)
    statistics.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 获取订单列表
const getOrderList = async () => {
  orderLoading.value = true
  try {
    const res = await getMerchantOrders(merchantId, orderQuery.value)
    orderList.value = res.data.list
    orderTotal.value = res.data.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
  } finally {
    orderLoading.value = false
  }
}

// 获取商品列表
const getProductList = async () => {
  productLoading.value = true
  try {
    const res = await getMerchantProducts(merchantId, productQuery.value)
    productList.value = res.data.list
    productTotal.value = res.data.total
  } catch (error) {
    console.error('获取商品列表失败:', error)
  } finally {
    productLoading.value = false
  }
}

// 获取评价列表
const getReviewList = async () => {
  reviewLoading.value = true
  try {
    const res = await getMerchantReviews(merchantId, reviewQuery.value)
    reviewList.value = res.data.list
    reviewTotal.value = res.data.total
  } catch (error) {
    console.error('获取评价列表失败:', error)
  } finally {
    reviewLoading.value = false
  }
}

// 返回按钮点击
const goBack = () => {
  router.back()
}

// 编辑按钮点击
const handleEdit = () => {
  router.push(`/merchant/edit/${merchantId}`)
}

// 查看订单详情
const handleViewOrder = (row) => {
  router.push(`/order/detail/${row.id}`)
}

// 查看商品详情
const handleViewProduct = (row) => {
  router.push(`/product/detail/${row.id}`)
}

// 回复评价
const handleReplyReview = (row) => {
  replyForm.value = {
    reviewId: row.id,
    replyContent: row.replyContent || ''
  }
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyFormRef.value) return
  
  await replyFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await replyMerchantReview(replyForm.value.reviewId, {
          replyContent: replyForm.value.replyContent
        })
        ElMessage.success('回复成功')
        replyDialogVisible.value = false
        getReviewList()
      } catch (error) {
        console.error('回复失败:', error)
        ElMessage.error('回复失败')
      }
    }
  })
}

// 订单分页
const handleOrderSizeChange = (val) => {
  orderQuery.value.pageSize = val
  getOrderList()
}

const handleOrderCurrentChange = (val) => {
  orderQuery.value.pageNum = val
  getOrderList()
}

// 商品分页
const handleProductSizeChange = (val) => {
  productQuery.value.pageSize = val
  getProductList()
}

const handleProductCurrentChange = (val) => {
  productQuery.value.pageNum = val
  getProductList()
}

// 评价分页
const handleReviewSizeChange = (val) => {
  reviewQuery.value.pageSize = val
  getReviewList()
}

const handleReviewCurrentChange = (val) => {
  reviewQuery.value.pageNum = val
  getReviewList()
}

// 标签页切换
const handleTabChange = (tab) => {
  switch (tab) {
    case 'orders':
      getOrderList()
      break
    case 'products':
      getProductList()
      break
    case 'reviews':
      getReviewList()
      break
  }
}

onMounted(() => {
  getMerchantInfo()
  getStatisticsData()
  getOrderList()
})
</script>

<style lang="scss" scoped>
.merchant-detail {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .mt-20 {
    margin-top: 20px;
  }
  
  .statistics-cards {
    .statistics-card {
      .card-header {
        font-size: 14px;
        color: #606266;
      }
      
      .card-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        text-align: center;
        padding: 10px 0;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .license-image {
    width: 100px;
    height: 100px;
    object-fit: cover;
  }
  
  .review-image {
    width: 60px;
    height: 60px;
    object-fit: cover;
  }
  
  .amount {
    color: #f56c6c;
    font-weight: bold;
  }
  
  .dialog-footer {
    text-align: right;
  }
}
</style> 